<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
-->
<!-- 
* @desc:用户管理新增or编辑弹窗
* @fileName:Operation.vue
* @author:chenxiaofeng@yzbdl.ac.cn
* @date:2022-4-15
!-->
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import http from "@/services/common/http";
import { showErrorMessage } from "@/common/message";
const props = defineProps({
  // 角色下拉下拉值
  roleList: Array as any,
  // 新增用户方法回调
  saveUser: Function as any,
  // 修改用户方法回调
  editUser: Function as any,
  // 修改用户当前行数据
  oneUserInfo: Object as any,
  // 新增或修改文字
  addOrEdit: String,
});

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const labelPosition = ref("top");

/**
 * 表单数据
 */
const ruleForm = reactive({
  userName: "",
  nickName: "请选择账号",
  userId: "",
  role: [],
});

/**
 * 定义校验规则
 */
const rules = reactive({
  userId: [{ required: true, message: "请选择用户账号", trigger: "blur" }],
});

/**
 * 提交表单
 * @param formEl 表单数据
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.addOrEdit === "新增") {
        let saveObj = {
          roleIds: ruleForm.role,
          userId: ruleForm.userId,
        };
        if (
          saveObj.userId !== "" &&
          saveObj.userId !== null &&
          typeof saveObj.userId !== "undefined"
        ) {
          props.saveUser(saveObj);
        }
      } else {
        let editObj = {
          userId: props.oneUserInfo.id,
          roleIds: ruleForm.role,
        };
        props.editUser(editObj);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description: 获取账号列表
 * @param {string} queryString
 * @param {any} cb
 * @return void
 */
const querySearchAsync = (queryString: string, cb: any) => {
  ruleForm.nickName = "请选择账号";
  let results: any = [];
  if (queryString === "") {
    cb(results);
  } else {
    http
      .post({
        url: `/user/notInOrg?likeName=` + queryString,
      })
      .then((res: any) => {
        if (res.code === 200) {
          results = res.data;
          cb(results);
        }
      })
      .catch((err: any) => {
        showErrorMessage({ message: err.data });
      });
  }
};

/**
 * @description: 选中账号
 * @param {any} item
 * @return void
 */
const handleSelect = (item: any) => {
  ruleForm.userName = item.userName;
  ruleForm.nickName = item.nickName;
  ruleForm.userId = item.id;
};

/**
 * @description: 处理删除选中账号后，初始化昵称
 * @param {any} val
 * @return void
 */
const changeSelect = (val: any) => {
  if (val === "" || val === null || typeof val === undefined) {
    ruleForm.nickName = "请选择账号";
  }
};

onMounted(() => {
  let userInfo = { ...props.oneUserInfo };
  if (JSON.stringify(props.oneUserInfo) !== "{}") {
    ruleForm.userName = userInfo.userName;
    ruleForm.nickName = userInfo.nickName;
    ruleForm.role = userInfo.roles.map((item: any) => {
      return item.id;
    });
  }
});
</script>

<template>
  <div class="operation">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :label-position="labelPosition"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
    >
      <el-form-item label="用户账号" prop="userId">
        <el-autocomplete
          v-model="ruleForm.userName"
          :trigger-on-focus="false"
          :disabled="props.addOrEdit !== '新增'"
          clearable
          @select="handleSelect"
          @change="changeSelect"
          :fetch-suggestions="querySearchAsync"
          style="width: 100%"
          placeholder="请输入用户账号"
        >
          <template #default="{ item }">
            <div class="value">{{ item.userName }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <span class="pl10">{{ ruleForm.nickName }}</span>
      </el-form-item>
      <el-form-item label="用户所属角色" prop="role">
        <el-select
          v-model="ruleForm.role"
          size="large"
          multiple
          collapse-tags
          collapse-tags-tooltip
          style="width: 100%"
        >
          <el-option
            v-for="item in props.roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="click-button">
        <el-button @click="submitForm(ruleFormRef)">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.pl10 {
  padding-left: 10px;
}
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.click-button {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
</style>
